package com.tiancheng.trade.payment.channel.umsmop.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.tiancheng.trade.payment.channel.umsmop.response.TokenResponse;

import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: ZHANGWEI
 * Date: 2016/12/6
 * Time: 11:01
 * 所属模块：
 * 功能说明：cache缓存
 */
public class OpenApiCache {

    public final static int MAX_PROCESS_TIMEOUT = 3600;

    public static Cache<String, Object> contextCache = CacheBuilder.newBuilder()
            .expireAfterWrite(MAX_PROCESS_TIMEOUT, TimeUnit.SECONDS).build();

    /**
     * 获取当前有效的token
     * @param context
     * @return
     */
    public static TokenResponse getCurrentToken(OpenApiContext context){
        String appId = context.getAppId();
        TokenResponse token = (TokenResponse)contextCache.getIfPresent(appId);
        if(token==null){
            token = OpenTokenUtil.getToken(context);
            contextCache.put(context.getAppId(), token);
        }
        context.setCurrentToken(token);
        return token;
    }
}
